<!--
界面中可以实现如下操作:
  // <<< XX仓库 >>> XX表示原料\包材\线缆
  // XX仓库>生产单待出库
  waitOutStoreByProductionOrder: 'waitOutStoreByProductionOrder',
  // XX仓库>生产单已出库
  completedOutStoreByProductionOrder: 'completedOutStoreByProductionOrder',

  // <<<成品仓库>>>
  // 海外仓生产单待入库
  inStoreOfOverseasByProductionOrder: 'inStoreOfOverseasByProductionOrder',

  // <<<生产中心>>>
  // 生产中心>生产单池
  inPoolProductionOrder: 'inPoolProductionOrder',
  // 生产中心>进行中生产单
  inProgressProductionOrder: 'inProgressProductionOrder',
  // 生产中心>已完结生产单
  completedProductionOrder: 'completedProductionOrder',
-->

<template>
	<a-card :bordered="false">
		<div class="table-page-search-wrapper">
			<a-form layout="inline">
				<a-row :gutter="48">

					<a-col :md="8" :sm="24">
						<a-form-item label="生产单号">
							<a-input v-model="queryParam.orderNumber" placeholder="请输入生产单号" />
						</a-form-item>
					</a-col>

					<!-- <a-col :md="4" :sm="24" v-show="$isDev"> -->
					<!--            <a-input v-model="queryParam.orderType" placeholder="请输入订单类型"/>-->
					<!-- <a-form-item label="订单类型">
              <a-select :default-value="orderType" v-model="queryParam.orderType"
                        style="width: 120px">
                <a-select-option :value="item.id" v-for="(item, index) in orderTypeList">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->

					<!-- <a-col :md="4" :sm="24" v-show="$isDev">
            <a-form-item label="执行状态">
              <a-select :default-value="executeStatus" v-model="queryParam.executeStatus"
                        style="width: 120px">
                <a-select-option :value="id" v-for="{id, name, code} in executeStatusList">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->

					<a-col :md="!advanced && 8 || 24" :sm="24">
						<span class="table-page-search-submitButtons"
							:style="advanced && { float: 'right', overflow: 'hidden' } || {}">
							<a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
							<!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
						</span>
					</a-col>

					<a-col :md="24" :sm="24">
						<a-form-item label="归属公司：">
							<FCOrgRadioGroup v-model="queryParam.orgId" :filter-types="[$businessEnum.ORG_TYPE_ENUM.COMPANY.id]" />
							<!--              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdCompany">-->
							<!--                <a-radio-button value="">-->
							<!--                  全部-->
							<!--                </a-radio-button>-->
							<!--                <a-radio-button :value="id" v-for="{id, name} in orgs">-->
							<!--                  {{ name }}-->
							<!--                </a-radio-button>-->
							<!--              </a-radio-group>-->

						</a-form-item>
					</a-col>

					<a-col :md="24" :sm="24" v-if="viewState == $util.EMS_ORDER_VIEW_STATE.inPoolProductionOrder">
						<a-form-item label="是否可用：">
							<a-radio-group :default-value="null" button-style="solid" v-model="queryParam.status">
								<a-radio-button :value="null">全部</a-radio-button>
								<a-radio-button :value="0">可用</a-radio-button>
								<a-radio-button :value="1">不可用</a-radio-button>
							</a-radio-group>
						</a-form-item>
					</a-col>

				</a-row>
			</a-form>
		</div>

		<div class="table-operator">
			<template v-if="viewState == $util.EMS_ORDER_VIEW_STATE.inPoolProductionOrder">
				<a-button type="primary" @click="handleScheduleProductionShow">排单生产</a-button>
				<a-button type="primary" @click="handleRecommendedProduction">推荐生产</a-button>
				<a-button type="primary" @click="handleMaterialCalculation">物料计算</a-button>
				<a-button type="primary" @click="$refs.addForm.add({ orderType })" style="float: right;">录入</a-button>
			</template>
		</div>

		<s-table ref="table" size="default" :columns="columnsDynamic" :data="loadData" :alert="true"
			:rowKey="(record) => record.orderId"
			:rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">

			<span slot="status" slot-scope="text, record">
				<a-switch v-model:checked="record.status == 0" :loading="record.loading"
					@change="onOrderStatusChange($event, record)" />
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.waitOutStoreByProductionOrder" slot-scope="text, record">
				<a @click="$refs.productionOrderMaterialsOutStoreAddForm.show(record, '出库', '',
					{ viewState: $refs.productionOrderMaterialsOutStoreAddForm.viewStateEnum.materialOut, materialType })">
					出库</a>
				<a-divider type="vertical" />
				<a
					@click="$refs.productionOrderMaterialsOutStoreDetailForm.show(record, '出库详情', 'materialOut', { materialType })">
					出库详情</a>
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.completedOutStoreByProductionOrder" slot-scope="text, record">
				<template v-if="materialType != $businessEnum.MATERIAL_TYPE_ENUM.packing.id">
					<!--     生产单已出库   -->
					<a
						@click="$refs.productionOrderMaterialsOutStoreDetailForm.show(record, '出库详情', '', { materialType })">出库详情</a>
					<a-divider type="vertical" />
					<!--    实际上是查出库订单,显示订单Modal    -->
					<a
						@click="$refs.outStoreOrderModal.show(record, '出库明细', 'outOrder', { 'orderType': $businessEnum.ORDER_TYPE_ENUM.outOrder.id })">出库明细</a>
				</template>
				<template v-else>
					<!--     生产单已出库(包材)   -->
					<a @click="$refs.packingOutInfo.show(record, '出库详情', '', { materialType })">出库详情</a>
					<a-divider type="vertical" />
					<!--    实际上是查出库订单,显示订单Modal    -->
					<a
						@click="$refs.outStoreOrderModal.show(record, '出库明细', 'outOrder', { 'orderType': $businessEnum.ORDER_TYPE_ENUM.outOrder.id })">出库明细</a>

				</template>
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.inPoolProductionOrder" slot-scope="text, record">
				<template v-if="record.isOverseasStore == 'N'">
					<a @click="$refs.editForm.disabledShow(record)">详情</a>
					<a-divider type="vertical" />
					<a @click="$refs.editForm.edit(record)">订单编辑</a>
					<a-divider type="vertical" />
					<a @click="$refs.productionMaterialListForm.show(record,
						{ title: '产品列表', viewState: 'productionPool', materialType: $businessEnum.MATERIAL_TYPE_ENUM.product.id })">
						产品列表</a>
					<a-divider type="vertical" />
					<a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
						<a>删除</a>
					</a-popconfirm>
				</template>
				<template v-else>
					<a @click="$refs.editForm.disabledShow(record)">详情</a>
					<a-divider type="vertical" />
					<a @click="$refs.editForm.edit(record)">订单编辑</a>
					<a-divider type="vertical" />
					<a
						@click="$refs.productionMaterialListForm.show(record,
							{ title: '产品列表', viewState: 'productionPool', materialType: $businessEnum.MATERIAL_TYPE_ENUM.overseasProduct.id })">
						产品列表</a>
					<a-divider type="vertical" />
					<a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
						<a>删除</a>
					</a-popconfirm>
				</template>
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.inProgressProductionOrder" slot-scope="text, record">
				<a @click="$refs.editForm.disabledShow(record)">详情</a>
				<a-divider type="vertical" />
				<template v-if="record.isOverseasStore == 'N'">
					<a @click="$refs.orderMaterialIndexModal.show(record,
						{ title: '产品列表', viewState: 'inProduction', materialType: $businessEnum.MATERIAL_TYPE_ENUM.product.id })">
						产品列表
					</a>
				</template>
				<template v-else>
					<a @click="$refs.productListModal.show(record)">
						产品列表
					</a>
				</template>
				<a-divider type="vertical" />
				<a @click="$refs.productionOrderOutForm.show(record, '包材列表', 'packingOutReadonly')">包材列表</a>
			</span>

			<span :slot="$util.EMS_ORDER_VIEW_STATE.completedProductionOrder" slot-scope="text, record">
				<a @click="$refs.editForm.disabledShow(record)">详情</a>
				<!--        <a-divider type="vertical"/>-->
				<!--        <a @click="">交付</a>-->
				<!--        <a-divider type="vertical"/>-->
				<!--        <a @click="">专箱清单</a>-->
				<a-divider type="vertical" />
				<a
					@click="$refs.orderMaterialIndexModal.show(record,
						{ title: '产品列表', viewState: 'productionCompleted', materialType: record.isOverseasStore == 'Y' ? $businessEnum.MATERIAL_TYPE_ENUM.overseasProduct.id : $businessEnum.MATERIAL_TYPE_ENUM.product.id })">
					产品列表
				</a>
				<a-divider type="vertical" />
				<a @click="$refs.productionOrderOutForm.show(record, '包材列表', 'packingOutReadonly')">包材列表</a>
			</span>

		</s-table>

		<add-form ref="addForm" @ok="handleOk" />
		<edit-form ref="editForm" @ok="handleOk" />

		<!--  生产单出库操作页  -->
		<production-order-materials-out-store-add-form ref="productionOrderMaterialsOutStoreAddForm" />
		<!--  生产单出库详情页  -->
		<production-order-materials-out-store-detail-form ref="productionOrderMaterialsOutStoreDetailForm" />
		<out-store-order-modal ref="outStoreOrderModal" />

		<!--  生产单产品  -->
		<order-material-index-modal ref="orderMaterialIndexModal" @ok="handleOk" />
		<!--  排单生产提示  -->
		<a-modal title="提示" :visible="scheduleProductionVisible" @ok="handleOkByScheduleProduction"
			@cancel="scheduleProductionVisible = false">
			<p>确认将选择的生产单进行排单生产吗?</p>
		</a-modal>
		<!--  推荐生产  -->
		<!--  物料计算  -->
		<material-calculation-form ref="materialCalculationForm" @ok="handleOk" />
		<!--  生产单物料出库  -->
		<production-order-out-form ref="productionOrderOutForm" @ok="handleOk" :readonly="true" />
		<!--  产品完成  -->
		<product-complete-form ref="productCompleteForm" @ok="handleOk" />
		<!--  生产单中物料列表页  -->
		<production-material-list-form ref="productionMaterialListForm" @ok="handleOk" />
		<material-calculation-form ref="materialCalculationForm" @ok="handleOk" />

		<packing-out-info ref="packingOutInfo" />
		<product-list-modal ref="productListModal" />
		<recommend-production ref="recommendProduction" />
	</a-card>
</template>

<script>
import { STable } from '@/components'
import { page, changeStatus, del, doScheduleProduction, doRecommendedProduction, doMaterialCalculation } from '@/api/modular/main/emsorder/emsOrderManage'
import { list as emsOrgList } from '@/api/modular/main/emsorg/emsOrgManage'
import { EMS_ORDER_VIEW_STATE, getUrlParam } from '@/utils/util'
import FCOrgRadioGroup from '@/components/FcOrgRadioGroup/FCOrgRadioGroup'


// 生产中心>生产单待出库单   生产单物料出库操作页
import productionOrderMaterialsOutStoreAddForm from '@/views/main/emsordermaterial/productionOrder/emsOutStoreAddForm'
import productionOrderMaterialsOutStoreDetailForm from '@/views/main/emsordermaterial/productionOrder/emsOutStoreDetailForm'
import outStoreOrderModal from './emsProductionOrderOutStoreOrderModal.vue'
import packingOutInfo from '@/views/main/packingStorehouse/outedProductionOrder/outInfo'

// 生产中心>进行中生产单>[包材出库]
import productionOrderOutForm from '@/views/main/emsordermaterial/emsOrderMaterialProductionOrderOutForm'
import productCompleteForm from '@/views/main/emsordermaterial/emsOrderMaterialProductCompleteForm'

import addForm from '@/views/main/emsorder/emsOrderAddForm'
import editForm from '@/views/main/emsorder/emsOrderEditForm'
import productionMaterialListForm from '@/views/main/emsordermaterial/productionOrder/emsProductionMaterialListForm'
import materialCalculationForm from '@/views/main/emsorder/emsOrderMaterialCalculationForm'
import orderMaterialIndexModal from '@/views/main/emsordermaterial/emsOrderMaterialIndexModal'

import productListModal from '@/views/main/productionCenter/productionOrderInProgress/productListModal'
import RecommendProduction from '@/views/main/productionCenter/productionOrderPool/recommendProduction'

export default {
	components: {
		RecommendProduction,
		STable,
		addForm,
		editForm,
		productionOrderMaterialsOutStoreAddForm,
		productionOrderMaterialsOutStoreDetailForm,
		outStoreOrderModal,
		productionMaterialListForm,
		materialCalculationForm,
		orderMaterialIndexModal,
		productionOrderOutForm,
		productCompleteForm,
		FCOrgRadioGroup,
		packingOutInfo,
		productListModal,

	},
	mounted() {
		console.log('路由信息1', this.$route.params)
	},
	data() {
		return {
			advanced: false, // 高级搜索 展开/关闭
			queryParam: { time: '' },  // 查询参数
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				// 如果是已完成生产单页面
				if (this.$route.params) {
					if (this.$route.params.year && this.$route.params.mounth) {
						this.queryParam.time = this.$route.params.year + '-' + this.$route.params.mounth
					} else {
						this.queryParam.time = ''
					}
				}
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					return res.data
				})
			},
			scheduleProductionVisible: false,
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			urlParam: {},
			columnsType: '',
			suppliers: [],
			orgs: [],
			viewState: '',
			materialType: '',
		}
	},
	watch: {
		'$route.path': function (newValue) {
			let urlParam = getUrlParam(this.$route.path)
			this.urlParam = urlParam
			let { orderType, executeStatus, columnsType, viewState, materialType, refCount } = urlParam
			this.columnsType = columnsType
			this.viewState = viewState
			this.materialType = materialType
			this.queryParam = { orderType: this.$businessEnum.ORDER_TYPE_ENUM.produceOrder.id, executeStatus: executeStatus || '' }


			setTimeout(() => {
				this.$refs.table.refresh(true)
				this.$refs.table.clearSelected()
			}, 100)
		}
	},
	computed: {
		routePath() {
			let urlParam = getUrlParam(this.$route.path)
			return urlParam
		},
		materialTypeUrlParam() {
			return this.routePath.materialType
		},
		materialTypeEnum() {
			return this.$util.findMaterialTypeById(this.materialType)
		},
		orderType() {
			return this.routePath.orderType
		},
		orderTypeList() {
			let result = []
			result.push({ id: '', name: '全部', code: 'all' })
			for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
				let value = this.$businessEnum.ORDER_TYPE_ENUM[key]
				result.push(value)
			}
			return result
		},
		executeStatus() {
			return this.urlParam.executeStatus
		},
		executeStatusList() {
			let result = []
			result.push({ id: '', name: '全部', code: 'all' })
			for (const key in this.$businessEnum.EXECUTE_STATUS_ENUM) {
				let value = this.$businessEnum.EXECUTE_STATUS_ENUM[key]
				result.push(value)
			}
			return result
		},
		columnsDynamic() {
			switch (this.viewState) {
				case this.$util.EMS_ORDER_VIEW_STATE.waitOutStoreByProductionOrder:
					this.queryParam.executeStatus = this.$businessEnum.EXECUTE_STATUS_ENUM.IN_PROGRESS.id
					return [
						{
							title: '序号', width: '80px',
							customRender: (text, record, index) => `${index + 1}`
						},
						{
							title: '生产单号',
							dataIndex: 'orderNumber'
						},
						// {
						//   title: '物料总数量',
						//   dataIndex: '',
						//   customRender: (text, record, index) => `【没算】`
						// },
						// {
						//   title: '出库数量',
						//   dataIndex: '',
						//   customRender: (text, record, index) => `【没算】`
						// },
						{
							title: '开始时间',
							dataIndex: 'createTime'
						},
						{
							title: '操作',
							dataIndex: 'action',
							width: '250px',
							scopedSlots: { customRender: this.$util.EMS_ORDER_VIEW_STATE.waitOutStoreByProductionOrder }
						}
					]
				case this.$util.EMS_ORDER_VIEW_STATE.completedOutStoreByProductionOrder:
					this.queryParam.executeStatus = this.$businessEnum.EXECUTE_STATUS_ENUM.IN_PROGRESS.id
					return [
						{
							title: '序号', width: '80px',
							customRender: (text, record, index) => `${index + 1}`
						},
						{
							title: '生产单号',
							dataIndex: 'orderNumber'
						},
						{
							title: '开始时间',
							dataIndex: 'createTime'
						},
						{
							title: '结束时间',
							dataIndex: ''
						},
						{
							title: '操作',
							dataIndex: 'action',
							width: '250px',
							scopedSlots: { customRender: this.$util.EMS_ORDER_VIEW_STATE.completedOutStoreByProductionOrder }
						}
					]
				case this.$util.EMS_ORDER_VIEW_STATE.inStoreOfOverseasByProductionOrder:
					// TODO 这里好像还没做
					return []
				case this.$util.EMS_ORDER_VIEW_STATE.inPoolProductionOrder:
					return [
						{
							title: '序号', width: '80px',
							customRender: (text, record, index) => `${index + 1}`
						},
						{
							title: '生产单号',
							dataIndex: 'orderNumber'
						},
						{
							title: '归属子公司',
							dataIndex: 'targetOrgName'
						},
						{
							align: 'center',

							title: '是否海外仓',
							dataIndex: 'isOverseasStore',
							customRender: (text, record, index) => record.isOverseasStore == 'Y' ? '是' : '否'
						},
						{
							title: '是否可用',
							dataIndex: 'status',
							scopedSlots: { customRender: 'status' }
						},
						{
							title: '是否海外仓',
							dataIndex: 'isOverseasStore',
							customRender: (text, record, index) => record.isOverseasStore == 'Y' ? '是' : '否'
						},
						{
							title: '录入时间',
							dataIndex: 'createTime'
						},
						{
							title: '预计完成时间',
							dataIndex: 'estimateCompletionTime'
						},
						{
							title: '操作',
							dataIndex: 'action',
							width: '280px',
							scopedSlots: { customRender: this.$util.EMS_ORDER_VIEW_STATE.inPoolProductionOrder }
						}
					]
				case this.$util.EMS_ORDER_VIEW_STATE.inProgressProductionOrder:
					return [
						{
							title: '序号', width: '80px',
							customRender: (text, record, index) => `${index + 1}`
						},
						{
							title: '生产单号',
							dataIndex: 'orderNumber'
						},
						{
							title: '归属子公司',
							dataIndex: 'orgName'
						},
						{
          align: 'center',
          
          title: '是否海外仓',
          dataIndex: 'isOverseasStore',
					customRender: (text, record, index) => record.isOverseasStore == 'Y' ? '是' : '否'
        },
						{
							title: '录入时间',
							dataIndex: 'createTime'
						},
						{
							title: '排单时间',
							dataIndex: 'inProgressTime'
						},
						{
							title: '操作',
							dataIndex: 'action',
							width: '250px',
							scopedSlots: { customRender: this.$util.EMS_ORDER_VIEW_STATE.inProgressProductionOrder }
						}
					]
				case this.$util.EMS_ORDER_VIEW_STATE.completedProductionOrder:
					return [
						{
							title: '序号', width: '80px',
							customRender: (text, record, index) => `${index + 1}`
						},
						{
							title: '生产单号',
							dataIndex: 'orderNumber'
						},
						{
							title: '归属子公司',
							dataIndex: 'targetOrgName'
						},
						{
          align: 'center',
          
          title: '是否海外仓',
          dataIndex: 'isOverseasStore',
					customRender: (text, record, index) => record.isOverseasStore == 'Y' ? '是' : '否'
        },
						{
							title: '录入时间',
							dataIndex: 'createTime'
						},
						{
							title: '排单时间',
							dataIndex: 'inProgressTime'
						},
						{
							title: '完结时间',
							dataIndex: 'completedTime'
						},
						{
							title: '操作',
							dataIndex: 'action',
							width: '250px',
							scopedSlots: { customRender: this.$util.EMS_ORDER_VIEW_STATE.completedProductionOrder }
						}
					]
				default:
					return []
			}
		}
	},
	created() {
		let urlParam = getUrlParam(this.$route.path)
		this.urlParam = urlParam
		let { orderType, executeStatus, columnsType, viewState, materialType, refCount } = urlParam
		this.columnsType = columnsType
		this.viewState = viewState
		this.materialType = materialType
		this.queryParam = {
			orderType: this.$businessEnum.ORDER_TYPE_ENUM.produceOrder.id,
			executeStatus: executeStatus || '',
			refCount
		}
		this.queryParam.refCount = refCount
	},
	methods: {
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
			this.$refs.table.clearSelected()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		onOrderStatusChange(checked, row) {
			row.loading = true
			let { orderId } = row
			let status = checked ? 0 : 1
			let parameter = { orderId, status }
			changeStatus(parameter).then(res => {
				this.handleOk()
			})
		},
		// 排单生产
		handleScheduleProductionShow() {
			if (this.validateScheduleProduction()) {
				this.scheduleProductionVisible = true
			}
		},
		validateScheduleProduction() {
			let selectedRows = this.selectedRows
			if (selectedRows.length == 0) {
				this.$message.error('请先选择要排单生产的订单')
				return false
			}
			let unavailableOrders = selectedRows.filter(value => value.status != 0)
			if (unavailableOrders.length > 0) {
				this.$message.error('订单状态必须为"可用"才可以进行排单')
				return false
			}
			return true
		},
		handleOkByScheduleProduction() {
			// 调接口,排单生产
			if (this.validateScheduleProduction()) {
				let orderIds = this.selectedRows.map(value => value.orderId).join(',')
				doScheduleProduction({ orderIds }).then(res => {
					this.$message.success(res.message)
					this.scheduleProductionVisible = false
					this.handleOk()
				})
			}
		},
		handleRecommendedProduction() {
			// 推荐生产
			if (this.selectedRows.length == 0) {
				this.$message.error('请先选择一条生产单')
				return
			} else if (this.selectedRows.length > 1) {
				this.$message.error('只能选择一条生产单')
				return
			}
			let parameter = this.selectedRows[0]
			this.$refs.recommendProduction.show(parameter)
		},
		handleMaterialCalculation() {
			// 物料计算
			let orderIds = this.selectedRows.map(row => row.orderId).join(',')
			if (orderIds == '') {
				this.$message.error('请先选择订单')
				return
			}
			this.$refs.materialCalculationForm.add(orderIds)
		},
		getSuppliers() {
			emsOrgList({ pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id }).then((res) => {
				this.suppliers = res.data
			})
		},
		getOrgs() {
			emsOrgList({ pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.COMPANY.id }).then((res) => {
				this.orgs = res.data
			})
		}
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
